<template>
  <div class="login-box">
    <div class="form-box">
      <p class="top-title">欢迎登录XXXX</p>
      <el-form
        ref="ruleFormRef"
        :model="userForm"
        status-icon
        :rules="rulesForm"
        label-width="80px"
        class="login-ruleForm"
      >
        <el-form-item label="账号：" prop="phone">
          <el-input v-model.trim="userForm.phone" />
        </el-form-item>
        <el-form-item label="密码：" prop="pwd">
          <el-input
            v-model.trim="userForm.pwd"
            type="password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            class="sub-btn"
            type="primary"
            @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import { validatePhone, validatePassword } from "@/util/fromRole";
import { userLogin } from "@/api/user";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
const router = useRouter(); //$router
const store = useStore();
const ruleFormRef = ref<FormInstance>();
// 表单对象
const userForm = reactive({
  phone: "15388646355",
  pwd: "123456yz",
});
// 表单验证
const rulesForm = reactive({
  phone: validatePhone(),
  pwd: validatePassword(),
});
// 登录事件
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      userLogin(userForm)
        .then((res: any) => {
          if (res.code == 200) {
            // 将用户信息进行保存
            localStorage.setItem("userInform", res.data);
            store.dispatch("setUserInform", { userInform: res.data });
            // 跳转页面
            router.push("/");
          }
        })
        .catch((err: any) => {
          console.log(err);
        });
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
</script>

<style lang="scss" scoped>
.login-box {
  height: 100%;
  width: 100%;
  background: url("../assets/bg.jpg");
  display: flex;
  align-items: center;
  justify-content: center;
  .form-box {
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    width: 30%;
    height: 32%;
    border-radius: 6px;
    .top-title {
      font-size: 25px;
      color: #111111;
      font-weight: bold;
      margin: 25px 0;
      text-align: center;
    }
    .login-ruleForm {
      margin: 10px 30px;
    }
    .sub-btn {
      width: 100%;
      margin-top: 10px;
    }
  }
}
</style>